<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryOrderRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入入库名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="入库编号" prop="type">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入入库编号"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleOrderQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetOrderQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['customer:store:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="订单名称" align="center" prop="name" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="入库状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="store_type" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row.id)" v-hasPermi="['customer:store:edit']" v-if="scope.row.status==='0'" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)" v-hasPermi="['customer:store:remove']" v-if="scope.row.status==='0'||scope.row.status==='2'">删除</el-button>
          <el-button link type="primary" icon="Document" @click="handleQuery(scope.row.id)" v-hasPermi="['customer:store:query']">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

   <!--详情页面-->
    <el-dialog  v-model="centerDialogVisible" title="入库清单" width="900" center>
       <div>
           <el-row  :gutter="20">
             <el-col :span="12">
               <el-form-item label="订单编号：" label-width="120px">
                 <el-input v-model="orderData.orderNo" disabled/>
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="订单名字：" label-width="120px">
                 <el-input v-model="orderData.name" disabled/>
               </el-form-item>
             </el-col>
           </el-row>
         <el-row  :gutter="20">
           <el-col :span="12">
               <el-form-item label="合同服务时间：" label-width="120px">
                 <el-input v-model="orderData.serviceTime" disabled/>
               </el-form-item>
             </el-col>
           <el-col :span="12">
             <el-form-item label="合同到期时间：" label-width="120px">
               <el-input v-model="orderData.expirationTime" disabled/>
             </el-form-item>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="合同金额：" label-width="120px">
               <el-input v-model="orderData.money" disabled/>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="日租费用：" label-width="120px">
               <el-input v-model="orderData.dailyRent" disabled/>
             </el-form-item>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="仓库名称：" label-width="120px" v-if="getWarehouseId(orderData.warehouseId)>=0">
               <el-input v-model="warehouseList[getWarehouseId(orderData.warehouseId)].name" disabled/>
             </el-form-item>
           </el-col>
         </el-row>
       </div>
       <span style="font-size: 20px">储存商品清单:</span>
      <el-table v-loading="loading" :data="orderData.orderNumber">
        <el-table-column label="商品名称" align="center" prop="name">
        <template #default="scope">
          <el-tag >{{getGood(scope.row.goodsId).name}}</el-tag>
        </template>
        </el-table-column>
        <el-table-column label="商品规格" align="center" prop="specs" >
          <template #default="scope">
            <el-tag >{{getGood(scope.row.goodsId).specs}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品类别" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="goods_type" :value="getGood(scope.row.goodsId).type"/>
          </template>
        </el-table-column>
        <el-table-column label="存储商品数量" align="center" prop="number"/>
      </el-table>
    </el-dialog>

     <!--修改商品对话框-->
    <el-dialog title="修改入库清单页面" v-model="openUpdate" width="900px" append-to-body>
      <el-table v-loading="loading" :data="orderData.orderNumber">
        <el-table-column label="商品名称" align="center" prop="name">
          <template #default="scope">
            <el-tag >{{getGood(scope.row.goodsId).name}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" align="center" prop="specs" >
          <template #default="scope">
            <el-tag >{{getGood(scope.row.goodsId).specs}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品类别" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="goods_type" :value="getGood(scope.row.goodsId).type"/>
          </template>
        </el-table-column>
        <el-table-column label="存储商品数量" align="center" prop="number">
          <template #default="scope">
            <el-input-number v-model="scope.row.number" :min="1"/>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="update">确 定 修 改</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--合同页面-->
    <el-dialog  v-model="openUpdateContract" width="500px" append-to-body>
      <el-tabs type="border-card">
        <el-form ref="contractRef" :model="orderData" :rules="orderData.rules" label-width="120px">
          <el-row>
            <el-col>
              <el-form-item label="合同类型" prop="type">
                <el-radio-group v-model="orderData.type" disabled>
                  <el-radio label="0">存储合同</el-radio>
                  <el-radio label="1">出租合同</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col >
              <el-form-item label="入库清单名称" prop="name" style="width: 270px">
                <el-input v-model="orderData.name"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="合同开始时间" prop="serviceTime">
              <el-date-picker
                  v-model="orderData.serviceTime"
                  type="date"
                  placeholder="请选择合同开始时间"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="合同结束时间" prop="expirationTime">
              <el-date-picker
                  v-model="orderData.expirationTime"
                  type="date"
                  placeholder="请选择合同结束时间"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-row>
          <el-col span="12">
            <el-form-item label="仓库名称" prop="warehouseId">
              <el-select  style="width: 150px" placeholder="请选择仓库" v-model="orderData.warehouseId" clearable>
                <el-option
                    v-for="item in warehouseList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-row  v-if="orderData.type==='1'">
            <el-col span="12">
              <el-form-item label="仓库价格" v-if="orderData.warehouseId!=null">
                <el-input disabled v-model="warehouseList[getWarehouseId(orderData.warehouseId)].storageFee"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-else>
            <el-form-item label="货架价格" prop="dailyRent">
              <el-select  style="width: 200px" placeholder="请选择货架价格" v-model="orderData.dailyRent" clearable>
                <el-option
                    v-for="dict in shelf_prices"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item label="合同金额">
            <el-input v-model="orderData.money" disabled />
          </el-form-item>
        </el-form>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpdate">确 定 提 交</el-button>
          <el-button @click="openUpdate=true;openUpdateContract=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加商品对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form :model="queryParams" ref="queryGoodsRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="商品名称" prop="name">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter="handleGoodsQuery"
          />
        </el-form-item>
        <el-form-item label="商品类别" prop="type">
          <el-select v-model="queryParams.type" style="width: 150px" placeholder="请选择商品类别" clearable>
            <el-option
                v-for="dict in goods_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleGoodsQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetGoodsQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionGoodsChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="商品名称" align="center" prop="name" />
        <el-table-column label="商品规格" align="center" prop="specs" />
        <el-table-column label="商品类别" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="goods_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="存储商品数量" align="center">
          <template #default="scope">
            <el-input-number min="0"  v-model="goodsNum[getGoodNumber(scope.row.id)].number"/>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitGoods">确 定 添 加</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getGoodsList"
      />
    </el-dialog>
    <!--合同页面-->
    <el-dialog  v-model="openContract" width="500px" append-to-body>
      <el-tabs type="border-card">
          <el-form ref="contractRef" :model="orderData" :rules="orderData.rules" label-width="120px">
           <el-row>
             <el-col>
               <el-form-item label="合同类型" prop="type">
                 <el-select  style="width: 150px" placeholder="请选择合同类型" v-model="orderData.type" clearable>
                   <el-option
                       v-for="dict in contract_status"
                       :key="dict.value"
                       :label="dict.label"
                       :value="dict.value"
                   />
                 </el-select>
               </el-form-item>
             </el-col>
             <el-col >
               <el-form-item label="入库清单名称" prop="name" style="width: 270px">
                 <el-input v-model="orderData.name" placeholder="请输入入库清单名称" />
               </el-form-item>
             </el-col>
           </el-row>
            <el-row>
               <el-form-item label="合同开始时间" prop="serviceTime">
                 <el-date-picker
                  v-model="orderData.serviceTime"
                  type="date"
                  placeholder="请选择合同开始时间"
                  value-format="YYYY-MM-DD"
                />
               </el-form-item>
               <el-form-item label="合同结束时间" prop="expirationTime">
                <el-date-picker
                  v-model="orderData.expirationTime"
                  type="date"
                  placeholder="请选择合同结束时间"
                  value-format="YYYY-MM-DD"
                 />
               </el-form-item>
             </el-row>
            <el-col span="12">
              <el-form-item label="仓库名称" prop="warehouseId">
                <el-select  style="width: 150px" placeholder="请选择仓库" v-model="orderData.warehouseId" clearable>
                  <el-option
                      v-for="item in warehouseList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
              <el-row  v-if="orderData.type==='1'">
                  <el-col span="12">
                    <el-form-item label="仓库价格" v-if="orderData.warehouseId!==null">
                     <el-input disabled v-model="warehouseList[getWarehouseId(orderData.warehouseId)].storageFee"/>
                    </el-form-item>
                  </el-col>
              </el-row>
              <el-row v-else>
                <el-form-item label="货架价格" prop="dail  yRent">
                  <el-select  style="width: 200px" placeholder="请选择货架价格" v-model="orderData.dailyRent" clearable>
                    <el-option
                        v-for="dict in shelf_prices"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-row>
            <el-form-item label="合同金额">
              <el-input v-model="orderData.money" disabled />
            </el-form-item>
           </el-form>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitOrder">确 定 提 交</el-button>
          <el-button @click="cancelOrder">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Store">
import {addStore, listStore,getStore,updateStore,delStore} from "@/api/customer/store";
import {listGoods} from "@/api/customer/goods";
import {listWarehouse} from "@/api/warehouseManagement/warehouse";
import user from "@/store/modules/user";
import {ElMessage} from 'element-plus'

const { proxy } = getCurrentInstance();
const { goods_type,store_type,contract_status,shelf_prices } = proxy.useDict('goods_type',"store_type","contract_status","shelf_prices");


//存储商品列表
const goodsList = ref([]);
//入库清单列表
const orderList = ref([]);
const open = ref(false);
const openContract = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const warehouseList=ref()
const goodsNumber=ref(0)
const centerDialogVisible=ref(false)
const openUpdate=ref(false)
const openUpdateContract=ref(false)

const orderData = ref({
  type:null,
  serviceTime:null,
  expirationTime:null,
  money:0,
  dailyRent:null,
  warehouseId:null,
  name:null,
  cId:Number.parseInt( user().id),
  orderNumber:[],
  contractId:null,
  rules:{
    type:[{required: true, message: "合同类型不能为空", trigger: "blur"}],
    serviceTime:[
        {required: true, message: "合同开始时间不能为空", trigger: "blur"},
        {validator: (rule, value, callback) => {
          if (value > orderData.value.expirationTime) {
            callback(new Error('合同开始时间不能晚于结束时间'));
          }else {
            callback();
          }
        }, trigger: 'blur'},
    ],
    expirationTime:[
        {required: true, message: "合同结束时间不能为空", trigger: "blur"},
        {validator: (rule, value, callback) => {
          if (value < orderData.value.serviceTime) {
            callback(new Error('合同结束时间不能早于开始时间'));
          } else {
            callback();
          }
        }, trigger: 'blur'}
    ],
    dailyRent:[{required: true, message: "租金不能为空", trigger: "blur"}],
    warehouseId:[{required: true, message: "仓库不能为空", trigger: "blur"}],
    name:[{required: true, message: "入库清单名称", trigger: "blur"}],
  }
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: null,
    orderNo: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

let goodsNum = ref([]);
/** 查询储存商品列表 */
function getGoodsList() {
  queryParams.value.cId=user().id;
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows;
    total.value = response.total;
    goodsNum.value=[]
    for (let i = 0; i < goodsList.value.length; i++) {
      const goods = {
        goodsId: goodsList.value[i].id,
        number: 0,
      }
      goodsNum.value.push(goods);
    }
    loading.value = false;
  });
}

/** 查询储存仓库价格列表 */
function getWarehouseList() {
  listWarehouse().then(response => {
    warehouseList.value=response.rows
  })
}
/** 查询入库清单列表 */
function getList() {
  queryParams.value.cId=user().id;
  listStore(queryParams.value).then(response => {
    orderList.value= response.rows;
    total.value = response.total;
  })
}

//根据商品编号返回商品数量
function getGoodNumber(id) {
  for (let i = 0; i < goodsNum.value.length; i++) {
    if (goodsNum.value[i].goodsId === id) {
      return i;
    }
  }
}

//根据仓库名称返回仓索引
function getWarehouseId(id) {
  for (let i = 0; i < warehouseList.value.length; i++) {
    if (warehouseList.value[i].id === id) {
      return i;
    }
  }
}

//根据商品编号返回商品
function getGood(id) {
  for (let i = 0; i < goodsList.value.length; i++) {
    if (goodsList.value[i].id === id) {
      return goodsList.value[i];
    }
  }
}

//查询订单详细信息
function orderQuery (id) {
  loading.value=true
  queryParams.value.cId=user().id;
  delete queryParams.value.pageNum
  delete queryParams.value.pageSize
  listGoods(queryParams.value).then(response => {
    goodsList.value = response.rows;
    getStore(id).then(response => {
      console.log(response.data.money)
      orderData.value.money=response.data.money
      console.log(orderData.value.money)
      orderData.value.type=response.data.type
      orderData.value.serviceTime=response.data.serviceTime
      orderData.value.expirationTime=response.data.expirationTime
      orderData.value.status=response.data.status
      orderData.value.orderNumber=response.data.orderNumber
      orderData.value.name=response.data.name
      orderData.value.orderNo=response.data.orderNo
      orderData.value.dailyRent=response.data.dailyRent+""
      orderData.value.warehouseId=response.data.warehouseId
      orderData.value.contractId=response.data.contractId
      loading.value = false;
    })
  });
}

function handleQuery(id){
  orderQuery(id)
  centerDialogVisible.value=true
}

//根据合同时间计算合同金额
function countMoney() {
  if(orderData.value.serviceTime!=null&&orderData.value.expirationTime){
    const serviceTime = new Date(orderData.value.serviceTime);
    const expirationTime = new Date(orderData.value.expirationTime);
    let days;
    if(orderData.value.serviceTime===orderData.value.expirationTime){
      days=1
    }else {
      days = (expirationTime - serviceTime) / (1000 * 60 * 60 * 24);
    }
    if(orderData.value.type=== '1' && orderData.value.warehouseId != null){
      orderData.value.dailyRent=warehouseList.value[getWarehouseId(orderData.value.warehouseId)].storageFee
      orderData.value.money = days * orderData.value.dailyRent;
    }
    if (orderData.value.type === '0' && orderData.value.dailyRent!= null) {
      orderData.value.money = days * Number.parseInt(orderData.value.dailyRent)*goodsNumber.value;
    }
  }
}

watch(orderData.value,(newValue,oldValue)=>{countMoney()})
watch(orderData.value.type,(newValue,oldValue)=>{orderData.value.dailyRent=null})
//计算商品逻辑
function countGoods() {
  if(ids.value.length>0){
    for (let i = 0; i < ids.value.length; i++) {
      orderData.value.orderNumber.push(goodsNum.value[getGoodNumber(ids.value[i])])
      goodsNumber.value+=Number.parseInt(goodsNum.value[getGoodNumber(ids.value[i])].number)
    }
  }else {
    for (let i = 0; i < orderData.value.orderNumber.length; i++) {
      goodsNumber.value+=Number.parseInt(orderData.value.orderNumber[i].number)
    }
  }
}


/**入库商品提交按钮*/
function submitGoods(){
  countGoods()
  if(orderData.value.orderNumber.length>0){
    open.value=false
    openContract.value=true
  }else {
    ElMessage({
      message: '请选择要存储的商品',
      type: 'warning'
    })
  }
}

/**入库清单提交按钮*/
function submitOrder(){
  proxy.$refs["contractRef"].validate(valid => {
    if (valid) {
      delete orderData.value.rules
      addStore(orderData.value).then(response => {
        proxy.$modal.msgSuccess("添加成功");
        openContract.value=false
        getList()
      })
      reset()
    }
  });
}

/**入库清单修改按钮*/
function submitUpdate(){
  proxy.$refs["contractRef"].validate(valid => {
    if (valid) {
      delete orderData.value.rules
      updateStore(orderData.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        openUpdateContract.value=false
        reset()
        getList()
      })
    }
  });
}

//重置
function reset() {
  proxy.resetForm("contractRef");
  proxy.resetForm("queryGoodsRef");
  openContract.value=false
  orderData.value.dailyRent=null
  orderData.value.money=0
  orderData.value.orderNumber=[]
  orderData.value.type=null
  orderData.value.warehouseId=null
  orderData.value.expirationTime=null
  orderData.value.serviceTime=null
}
// 取消按钮
function cancel() {
  open.value = false;
  openUpdate.value=false
  reset()
}
//取消订单
function cancelOrder(){
     openContract.value=false
     open.value=true
}
/** 商品搜索按钮操作 */
function handleGoodsQuery() {
  queryParams.value.pageNum = 1;
  getGoodsList();
}
/** 商品重置按钮操作 */
function resetGoodsQuery() {
  proxy.resetForm("queryGoodsRef");
  handleGoodsQuery();
}
/** 订单重置按钮操作 */
function resetOrderQuery() {
  proxy.resetForm("queryOrderRef");
  queryParams.value.orderNo=null
  handleOrderQuery();
}
/** 订单搜索按钮操作 */
function handleOrderQuery() {
  queryParams.value.pageNum = 1;
  getList()
}
// 商品多选框选中数据
function handleSelectionGoodsChange(selection) {
  ids.value = selection.map(item => item.id);
}

function update(){
   openUpdate.value=false
   openUpdateContract.value=true
   countGoods()
   countMoney()
}
/** 新增按钮操作 */
function handleAdd() {
  proxy.resetForm("queryGoodsRef");
  title.value = "选中商品，即是将此商品入库";
  open.value=true;
  getGoodsList(user().id)
}

/** 删除按钮操作 */
function handleDelete(id) {
  proxy.$modal.confirm('是否确认删除储存入库清单编号为"' + id + '"的数据项？').then(function() {
    getStore(id).then(response => {
      orderData.value.money=response.data.money
      orderData.value.type=response.data.type
      orderData.value.serviceTime=response.data.serviceTime
      orderData.value.expirationTime=response.data.expirationTime
      orderData.value.status=response.data.status
      orderData.value.orderNumber=response.data.orderNumber
      orderData.value.name=response.data.name
      orderData.value.orderNo=response.data.orderNo
      orderData.value.dailyRent=response.data.dailyRent+""
      orderData.value.warehouseId=response.data.warehouseId
      orderData.value.contractId=response.data.contractId
      delStore(orderData.value).then(response => {
        getList()
      })
    })
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}


/** 修改按钮操作 */
function handleUpdate(id) {
  orderQuery(id)
  openUpdate.value=true
}
onMounted(()=>getWarehouseList())
getList()
</script>
